<template>
  <div>
    <el-table :header-cell-style="{'text-align':'center'}" :cell-style="{'text-align':'center'}" v-loading="loading"
              :data="items" stripe border style="width: 100%">
      <el-table-column label="姓名" width="120">
        <template slot-scope="scope">
          {{ scope.row.name }}
          <el-tag v-if="scope.row.is_default" size="mini">默认联系人</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="gender_text" label="性别"/>
      <el-table-column prop="phone" label="联系电话" min-width="120"/>
      <el-table-column label="所属区域" min-width="170">
        <template slot-scope="scope">
          {{ scope.row.province_name }} {{ scope.row.city_name }}
          {{ scope.row.county_name }}
        </template>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" min-width="150"/>
      <el-table-column prop="update_time" label="创建时间" min-width="100"
                       :formatter="(row)=>row.update_time.slice(0,10)"/>
      <el-table-column label="操作" min-width="180" fixed="right">
        <template slot-scope="scope">
          <div class="flex" style="display: flex">
            <el-button type="primary" plain size="mini" :disabled="scope.row.is_default" class="px-1"
                       @click="setDefault(scope.row.id)" v-if="permission.includes('sys:customer_user:set_default')">
              设置为默认
            </el-button>
            <el-button size="mini" @click="removeCustomer(scope.row.id)"
                       v-if="permission.includes('sys:customer_user:delete')">删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import {mapGetters} from "vuex";

export default {
  name: "User",

  props: {
    id: {
      type: Number,
      default: 0
    }
  },
  computed: {
    ...mapGetters(["permission"])
  },

  data() {
    return {
      loading: false,
      items: []
    };
  },

  mounted() {
    this.loadData();
  },

  methods: {
    loadData() {
      this.loading = true;
      this.$http.get(`customers/${this.id}/users`).then((res) => {
        this.items = res.data.data;
        this.loading = false;
      });
    },

    setDefault(id) {
      this.loading = true;
      this.$http.put(`customers/${this.id}/default_user`, {customer_user_id: id}).then(() => {
        this.$message.success('设置成功');
        this.loadData();
      });
    },

    removeCustomer(id) {
      this.$confirm("确定删除该联系人吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$http.delete(`customer_users/${id}`).then(() => {
          this.$message.success("删除成功");
          this.loadData();
        });
      });
    }
  }
};
</script>
